package com.yingsheng.bi.hks.basic.utils;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtil {

    public static String getImageId(String imgPath, String POST_URL){
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost post = new HttpPost(POST_URL);
            File file = new File(imgPath);
            FileBody fileBody = new FileBody(file);
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("data", fileBody);
            post.setEntity(entity);
            HttpResponse response = httpclient.execute(post);
            HttpEntity r_entity = response.getEntity();
            String responseString = EntityUtils.toString(r_entity);
            log.info("返回结果：" + responseString);
            //你需要根据出错的原因判断错误信息，并修改
            httpclient.getConnectionManager().shutdown();
            file.delete();
            Gson gson = new Gson();
            Map<String, String> map = gson.fromJson(responseString, Map.class);
            return map.get("data");
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public static String post(Map<String, Object> params, String ocrUrl) throws Exception {

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        return PostHttpRequest(ocrUrl, pairs);
    }

    public static String PostHttpRequest(String Url, List<NameValuePair> params) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        //超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(300000)
                .setConnectTimeout(300000)
                .build();
        String result = null;
        try {
            HttpPost request = new HttpPost(Url);
            request.setConfig(requestConfig);
            request.setEntity(new UrlEncodedFormEntity(params, "UTF8"));
            HttpResponse respones = client.execute(request);
            if (respones.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(respones.getEntity(), "UTF8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        return result;
    }

    private static ArrayList<NameValuePair> covertParams2NVPS(
            Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<>();
        if (params == null || params.size() == 0) {
            return pairs;
        }
        for (Map.Entry<String, Object> param : params.entrySet()) {
            Object value = param.getValue();
            if (value instanceof String[]) {
                String[] values = (String[]) value;
                for (String v : values) {
                    pairs.add(new BasicNameValuePair(param.getKey(), v));
                }
            } else {
                if (value instanceof Integer) {
                    value = Integer.toString((Integer) value);
                } else if (value instanceof Long) {
                    value = Long.toString((Long) value);
                }
                pairs.add(new BasicNameValuePair(param.getKey(), (String) value));
            }
        }
        return pairs;
    }
}